package com.zyl.demo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhaoyl
 * @date 2024/5/15
 * @description 说明
 */
public class SaleTickeDemo {
    public static void main(String[] args) {
        //并发：多线程操作同一个资源类,把资源丢入线程。

        //Ticket ticket = new Ticket();//synchronized
        Ticket2 ticket = new Ticket2();//lock

        //开启三个线程卖票
        new Thread(()->{
            for (int i=1;i<30;i++){
                ticket.sale();
            }
            },"线程A").start();
        new Thread(()->{for (int i=1;i<30;i++) ticket.sale();},"线程B").start();
        new Thread(()->{for (int i=1;i<30;i++) ticket.sale();},"线程C").start();
    }
}


//资源类oop
class Ticket{
    //属性
    private int number = 50;
    //卖票方式:加锁synchronized
    public  void sale(){
        synchronized(this){
            if (number>0){
                System.out.println(Thread.currentThread().getName()+"卖出了第"+
                        (number--)+"号票，剩余"+number);
            }
        }
    }
}


//资源类oop
class Ticket2{
    //属性
    private int number = 50;
    //可重入锁:默认非公平锁
    Lock lock = new ReentrantLock();
    //卖票方式
    public  void sale(){
        lock.lock();//加锁
        try {
            //业务代码
            if (number>0){
                System.out.println(Thread.currentThread().getName()+"卖出了第"+
                        (number--)+"号票，剩余"+number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();//解锁
        }
    }
}
